<template>
  <a-form
    ref="fromRef"
    :model="formState"
    :label-col="{ span: 4 }"
    :wrapper-col="{ span: 20 }"
    autocomplete="off"
    @finish="onFinish"
  >
    <a-form-item label="上级机构" name="topMechanism">
      <a-input v-model:value="formState.topMechanism" disabled />
    </a-form-item>

    <a-form-item
      label="机构名称"
      name="mechanismName"
      :rules="[{ required: true, message: '请输入机构名称' }]"
    >
      <a-input
        v-model:value="formState.mechanismName"
        :disabled="props.mechanismData ? true : false"
      />
    </a-form-item>
    <a-form-item
      label="机构代码"
      name="mechanismcode"
      :rules="[{ required: true, message: '请输入机构代码' }]"
    >
      <a-input v-model:value="formState.mechanismcode" />
    </a-form-item>

    <a-form-item label="备注" name="remark">
      <a-input v-model:value="formState.remark" />
    </a-form-item>
    <a-form-item :wrapper-col="{ offset: 20, span: 4 }">
      <a-button type="primary" html-type="submit">创建</a-button>
    </a-form-item>
  </a-form>
</template>

<script setup lang="ts">
import { reactive, watch, ref, onMounted } from "vue";
import type { TreeDataList, FormState } from "./types/index";
import { message } from "ant-design-vue";

const props = defineProps<{
  createParent: string;
  parentId: string;
  mechanismData?: TreeDataList;
}>();
onMounted(() => {
  if (props.mechanismData !== undefined) {
    console.log('编辑');
    
    formState.mechanismName = props.mechanismData.name;
    formState.mechanismcode = props.mechanismData.mechanismcode;
    formState.remark = props.mechanismData.remark;
  }
});
const emit = defineEmits<{
  (e: "clouseDrawer"): void;
}>();

watch(
  () => props.createParent,
  newVal => {
    formState.topMechanism = newVal;
  }
);
const fromRef = ref();
const formState = reactive<FormState>({
  topMechanism: props.createParent,
  mechanismName: "",
  mechanismcode: "",
  remark: "",
});
const onFinish = () => {
  fromRef.value.validate().then((values: FormState) => {
    console.log(values);
    console.log(props.parentId);
    if (props.mechanismData) {
      fromRef.value.resetFields();
      emit("clouseDrawer");
      message.success("编辑成功");
    } else {
      // 在此发送请求
      fromRef.value.resetFields();
      emit("clouseDrawer");
      message.success("创建成功");
    }
  });
  // console.log("Success:", values);
  // formState.mechanismName = "";
  // formState.mechanismcode = "";
  // formState.remark = "";
  // emit("clouseDrawer");
  // message.success("创建成功");
};
</script>

<style scoped></style>
